package com.example.demo.zookeeper.mytest.lock;

import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author liweizhi
 * @date 2020/6/24
 */
public class ZkLockUtil {
    public static ZooKeeper zooKeeper;

    private static final String connectString = "192.168.200.11:2181,192.168.200.12:2181,192.168.200.13:2181,192.168.200.14:2181";
    private static final String lockRoot = "/mylock";
    public static final String theLockPath = "/mm";
    private static final int sessionTimeout = 30_000;

    public static ZooKeeper newZookeeper() {
        CountDownLatch cdl = new CountDownLatch(1);
        DefaultLockWatcher defaultLockWatcher = new DefaultLockWatcher();
        defaultLockWatcher.setCdl(cdl);
        try {
            zooKeeper = new ZooKeeper(connectString + lockRoot, sessionTimeout, defaultLockWatcher);
            cdl.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }
}
